package com.tucc.hello.leetcode.no401_800.no523;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("task");
//        // 1 2 3 4 10 10 4 3 2 9
//        int[] nums = JSONUtil.toList(FileUtil.readString("C:\\Users\\tucc38782\\Desktop\\test.txt", "utf8"),
//                Integer.class).stream().mapToInt(Integer::intValue).toArray();
//        int k = 2000000000;
        int[] nums =  {2, 6, 4};

        // 2 0 0
        int k = 6;
        System.out.println(solution.checkSubarraySum(nums, k));
        stopWatch.stop();
        System.out.println(stopWatch.prettyPrint());
    }

    public boolean checkSubarraySum(int[] nums, int k) {
        if (nums.length < 2) {
            return false;
        }
        int v = 0;
        int capacity = k * 4 / 3 + 1;
        if(capacity < 0){
            capacity = Integer.MAX_VALUE;
        }
        Map<Integer, Integer> map = new HashMap<>(capacity);
        map.put(0, -1);
        for (int i = 0; i < nums.length; i++) {
            v = (v + nums[i]) % k;
            Integer preIndex = map.get(v);
            if(preIndex != null){
                if(i - preIndex >= 2){
                    return true;
                }
            }
            else{
                map.put(v, i);
            }
        }
        return false;
    }

}
